#include "mainwindow.h"
#include "qmediaplaylist.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton_12,&QPushButton::clicked,this,&MainWindow::SlotButtonStart);
    connect(ui->pushButton_13,&QPushButton::clicked,this,&MainWindow::SlotButtonNext);
    connect(ui->pushButton_11,&QPushButton::clicked,this,&MainWindow::SlotButtonPrevious);
    init();     //初始化相关函数
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::init()
{
    PlayerList = new QMediaPlaylist;    //实例化播放器和播放列表
    Player = new QMediaPlayer;



    Player->setVolume(50);
    PlayerList->setCurrentIndex(0);

    Player->setPlaylist(PlayerList);    //将播放列表加载到播放器
    connect(PlayerList,SIGNAL(currentIndexChanged(int)),this,SLOT(onPlaylistChanged(int)));

    connect(Player,SIGNAL(positionChanged(qint64)),this,SLOT(onPositionChanged(qint64)));
    connect(Player,SIGNAL(durationChanged(qint64)),this,SLOT(onDurationChanged(qint64)));

    //构造函数中进行信号和槽的链接
    //connect 有不同的写法，replyFinished也就是replyFinished()。
    network_manager = new QNetworkAccessManager();
    network_request = new QNetworkRequest();
    connect(network_manager, &QNetworkAccessManager::finished, this, &MainWindow::replyFinished);
    network_manager2 = new QNetworkAccessManager();
    network_request2 = new QNetworkRequest();
    connect(network_manager2, &QNetworkAccessManager::finished, this, &MainWindow::replyFinished2);

    network_manager3 = new QNetworkAccessManager();
    network_request3 = new QNetworkRequest();
    connect(network_manager3, &QNetworkAccessManager::finished,this, &MainWindow::replyFinished3);




}


void MainWindow::SlotButtonStart()
{
    if(!isPlay)
    {
        isPlay = true;
        ui->pushButton_12->setStyleSheet("border-image: url(:/small photo/images/purse.png);");
        Player->play();
    }
    else
    {
        isPlay = false;
        ui->pushButton_12->setStyleSheet("border-image: url(:/small photo/images/btn_paly_h.png)");
        Player->pause();
        return;
    }
}
void MainWindow::SlotButtonPrevious()
{
    PlayerList->previous();
    PlayerList->previousIndex();
}
void MainWindow::SlotButtonNext()
{
    PlayerList->next();
    PlayerList->nextIndex();


}

void MainWindow::onDurationChanged(qint64 duration)
{
    ui->horizontalSlider->setMaximum(duration); //设置进度条最大值 也就是歌曲时长 ms
    int secs = duration/1000; //全部秒数
    int mins = secs/60;//分
    secs = secs % 60;//秒
    durationTime = QString::asprintf("%d:%d",mins,secs);
    ui->label_5->setText(durationTime);
}
void MainWindow::onPositionChanged(qint64 position)
{
    if(ui->horizontalSlider->isSliderDown())
        return;//如果手动调整进度条，则不处理
    ui->horizontalSlider->setSliderPosition(position);
    int secs = position/1000;
    int mins = secs/60;
    secs = secs % 60;
    positionTime = QString::asprintf("%d:%d",mins,secs);
    ui->label_4->setText(positionTime);
}
//点击搜索按钮调用该函数，参数为搜索框内容
void MainWindow::search(QString str)
{
    QString KGAPISTR1 = QString("http://mobilecdn.kugou.com/api/v3/search/song?format=json"
                                "&keyword=%1&page=1&pagesize=18").arg(str);
    network_request->setUrl(QUrl(KGAPISTR1));
    network_manager->get(*network_request);
}
//为了简化代码，只使用参数keyword


//槽函数
void MainWindow::replyFinished(QNetworkReply *reply)
{
    //获取响应的信息，状态码为200表示正常
    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    //无错误返回
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串
        qDebug()<<result;
        parseJson(result);//该函数用于解析api接口返回的json
    }
    else
    {
        //处理错误
        qDebug()<<"搜索失败";
    }
}

void MainWindow::parseJson(QString json)
{
    QString songname_original; //歌曲名
    QString singername;        //歌手
    QString hashStr;           //hash
    QString album_name;        //专辑
    int duration;          	   //时间
    QByteArray byte_array;
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array.append(json), &json_error);
    if (json_error.error == QJsonParseError::NoError)
    {
        if (parse_doucment.isObject())
        {
            QJsonObject rootObj = parse_doucment.object();
            if (rootObj.contains("data"))
            {
                QJsonValue valuedata = rootObj.value("data");
                if (valuedata.isObject())
                {
                    QJsonObject valuedataObject = valuedata.toObject();
                    if (valuedataObject.contains("info"))
                    {
                        QJsonValue valueArray = valuedataObject.value("info");
                        if (valueArray.isArray())
                        {
                            QJsonArray array = valueArray.toArray();
                            int size = array.size();
                            for (int i = 0; i < size; i++)
                            {
                                QJsonValue value = array.at(i);
                                if (value.isObject())
                                {
                                    QJsonObject object = value.toObject();
                                    if (object.contains("songname_original"))//歌曲名
                                    {
                                        QJsonValue AlbumID_value = object.take("songname_original");
                                        if (AlbumID_value.isString())
                                        {
                                            songname_original = AlbumID_value.toString();
                                        }
                                    }
                                    if (object.contains("singername"))//歌手
                                    {
                                        QJsonValue AlbumID_value = object.take("singername");
                                        if (AlbumID_value.isString())
                                        {
                                            singername = AlbumID_value.toString();
                                        }
                                    }
                                    if (object.contains("album_name"))//专辑
                                    {
                                        QJsonValue AlbumID_value = object.take("album_name");
                                        if (AlbumID_value.isString())
                                        {
                                            album_name = AlbumID_value.toString();
                                        }
                                    }
                                    if (object.contains("hash")) //hash
                                    {
                                        QJsonValue FileHash_value = object.take("hash");
                                        if (FileHash_value.isString())
                                        {
                                            hashStr = FileHash_value.toString();
                                            //用Vector保存每首歌曲的hash
                                            m_Vectorlist.append(FileHash_value.toString());
                                        }
                                    }
                                    if (object.contains("album_id"))
                                    {
                                        QJsonValue FileHash_value = object.take("album_id");
                                        if (FileHash_value.isString())
                                        {
                                            //用Vector保存每首歌曲的album_id
                                            m_ID.append(FileHash_value.toString());
                                        }
                                    }
                                    if (object.contains("duration"))//时长
                                    {
                                        QJsonValue AlbumID_value = object.take("duration").toInt();
                                        duration = AlbumID_value.toInt();
                                    }
                                    //将解析出的内容放到列表中
                                    ui->tableWidget->setItem(i,0,new QTableWidgetItem(songname_original));
                                    //文字居中
                                    ui->tableWidget->item(i,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
                                    ui->tableWidget->setItem(i,1,new QTableWidgetItem(singername));
                                    ui->tableWidget->item(i,1)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
                                    ui->tableWidget->setItem(i,2,new QTableWidgetItem(album_name));
                                    ui->tableWidget->item(i,2)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
                                    QString time = QString("%1:%2").arg(duration/60).arg(duration%60);
                                    ui->tableWidget->setItem(i,4,new QTableWidgetItem(time));
                                    ui->tableWidget->item(i,4)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    else
    {
        qDebug() << json_error.errorString();
    }
}











void MainWindow::on_tableWidget_cellDoubleClicked(int row, int column)
{
    //歌曲请求 row 是行号
    QString KGAPISTR1 =QString("http://www.kugou.com/yy/index.php?r=play/getdata"
                                "&hash=%1&album_id=%2&_=1497972864535").arg(m_Vectorlist.at(row)).arg(m_ID.at(row));
    network_request2->setUrl(QUrl(KGAPISTR1));
    //这句话很重要，我们手动复制url放到浏览器可以获取json，但是通过代码不行，必须加上下面这句才可以
    network_request2->setRawHeader("Cookie","kg_mid=2333");
    network_request2->setHeader(QNetworkRequest::CookieHeader, 2333);
    network_manager2->get(*network_request2);
}
void MainWindow::replyFinished2(QNetworkReply *reply)
{
    //获取响应的信息，状态码为200表示正常
    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    //无错误返回
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串
        parseJsonSongInfo(result);//解析json
    }
    else
    {
        //处理错误
        qDebug()<<"歌曲播放失败";
    }
}


void MainWindow::parseJsonSongInfo(QString json)
{
    QString audio_name;//歌手-歌名
    QString play_url;//播放地址
    QString img;
    QByteArray byte_array;
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array.append(json), &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        if(parse_doucment.isObject())
        {
            QJsonObject rootObj = parse_doucment.object();
            if(rootObj.contains("data"))
            {
                QJsonValue valuedata = rootObj.value("data");
                if(valuedata.isObject())
                {
                    QJsonObject valuedataObject = valuedata.toObject();
                    QString play_urlStr("");
                    if(valuedataObject.contains("play_url"))
                    {
                        QJsonValue play_url_value = valuedataObject.take("play_url");
                        if(play_url_value.isString())
                        {
                            play_urlStr = play_url_value.toString();      //歌曲的url
                            if(play_urlStr!="")
                            {
                                qDebug()<<play_urlStr;
                                Player->setMedia(QUrl(play_urlStr));
                                Player->setVolume(50);
                                Player->play();
                            }
                        }
                    }
                    if(valuedataObject.contains("audio_name"))
                    {
                        QJsonValue play_name_value = valuedataObject.take("audio_name");
                        if(play_name_value.isString())
                        {
                            QString audio_name = play_name_value.toString();    //歌曲名字
                            if(audio_name!="")
                            {
                                //显示
                                qDebug()<<audio_name;
                                ui->label_2->setText(audio_name);
                            }
                        }
                    }
                    //下一篇的歌词获取也是在这里添加代码
                    //图片显示代码在这里添加
                }
                else
                {
                    qDebug()<<"出错";
                }
            }
        }
    }
}
























    void MainWindow::on_pushButton_6_clicked()
    {
    showMinimized();
    }

    void MainWindow::on_pushButton_7_clicked()
    {
    close();
    }

void MainWindow::on_pushButton_41_clicked()
{
    showMaximized();
}


void MainWindow::on_horizontalSlider_sliderReleased()
{
    Player->setPosition(ui->horizontalSlider->value());
}




void MainWindow::on_horizontalSlider_2_valueChanged(int value)
{
    Player->setVolume(value);
}







void MainWindow::on_pushButton_10_clicked()
{
    if (valuedataObject.contains("img"))
    {
        QJsonValue play_name_value = valuedataObject.take("img");
        if (play_name_value.isString())
        {
            QString audio_name = play_name_value.toString();
            if (audio_name != "")
            {
                m_Jpg.append(audio_name);
                network_request3->setUrl(QUrl(audio_name));
                network_manager3->get(*network_request3);
            }
        }
    }
    }
void MainWindow::replyFinished3(QNetworkReply *reply)
{
    //获取响应的信息，状态码为200表示正常
    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    //无错误返回
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();  //获取字节
        //由于获取的图片像素过大，而我们显示的图片很小，所以我们需要压缩图片的像素，我们label的大小为45*45，所以我们把图片压缩为45*45
        QPixmap pixmap;
        QSize picSize(45,45);
        pixmap.loadFromData(bytes);
        //pixmap.save("url"); 也可以现在图片
        ui->label_10->setPixmap(pixmap.scaled(picSize));
    }
    else
    {
        //处理错误
        qDebug()<<"处理错误3";
    }
}

